package com.ecoolex.chinadutyfree.retailer.core.manager;

import java.time.Instant;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ecoolex.chinadutyfree.retailer.core.dao.GoodsBarcodeDAO;
import com.ecoolex.chinadutyfree.retailer.entity.GoodsBarcode;
import com.ecoolex.chinadutyfree.retailer.entity.GoodsBarcode.Column;
import com.ecoolex.chinadutyfree.retailer.entity.GoodsBarcodeExample;
import com.ecoolex.chinadutyfree.retailer.entity.GoodsProduct;
import com.ecoolex.framework.common.enums.ResultCode;
import com.ecoolex.framework.common.util.BizAssert;
import com.ecoolex.framework.common.util.Check;
import com.ecoolex.framework.common.util.CollectorUtil;


@Service
public class GoodsBarcodeManager {

	@Autowired
	private GoodsBarcodeDAO dao;

	public void update(GoodsProduct product, List<String> barcodeList, String updateUser) {
		List<GoodsBarcode> oldList = queryByProductId(product.getProductId());

		barcodeList.forEach(barcode -> {
			BizAssert.isTrue(Check.notNullOrTrimEmpty(barcode), ResultCode.VERIFY.build(10), "条码为空");
			GoodsBarcode record = oldList.stream().collect(CollectorUtil.first(b -> b.getBarCode().equals(barcode)));
			if (Check.notNull(record)) {
				oldList.remove(record);
			} else {
				record = new GoodsBarcode();
				record.setGoodsId(product.getGoodsId());
				record.setProductId(product.getProductId());
				record.setBarCode(barcode);
				record.setDeleted(GoodsBarcode.NOT_DELETED);
				record.setCreateUser(updateUser);
				record.setCreateTime(Date.from(Instant.now()));
				record.setUpdateUser(updateUser);
				record.setUpdateTime(Date.from(Instant.now()));
				dao.insert(record);
			}
		});

		// 删除多余的
		oldList.forEach(old -> delete(old, updateUser));
	}

	public void deleteByProductId(Integer productId, String updateUser) {
		queryByProductId(productId).forEach(barcode -> delete(barcode, updateUser));
	}

	private void delete(GoodsBarcode record, String updateUser) {
		record.setDeleted(GoodsBarcode.IS_DELETED);
		record.setUpdateUser(updateUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.updateByPrimaryKeySelective(record, Column.deleted, Column.updateUser, Column.updateTime);
	}

	public List<GoodsBarcode> queryByProductId(Integer productId) {
		GoodsBarcodeExample example = new GoodsBarcodeExample();
		example.createCriteria().andProductIdEqualTo(productId).andDeletedEqualTo(GoodsBarcode.NOT_DELETED);
		return dao.selectByExample(example);
	}
}